//
//  SEGOrderDetailController.m
//  Uhomebk
//
//  Created by mac on 2017/7/5.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "SEGOrderDetailController.h"
#import "SEGOrderTrackCell.h"
#import "SEGOrderDetailCell.h"
#import "SEGOrderSourceCell.h"
#import "SEGOrderDetailModel.h"
#import "SEGOrderDetailSectionHeadView.h"
#import "SEGOrderDetailButtonView.h"
#import "SEGOrderHandleController.h"
#import "SEGOrderDetailManager.h"
#import "SEGOrderPayViewController.h"
#import "SEGOrderCancelViewController.h"

static  NSString *const kSourceCellId = @"SEGOrderSourceCell";
static  NSString *const kDetailCellId = @"SEGOrderDetailCell";
static  NSString *const kDeviceCellId = @"SEGOrderDeviceCell";
static  NSString *const kTrackCellId = @"SEGOrderTrackCell";

@interface SEGOrderDetailController ()<
UITableViewDelegate,
UITableViewDataSource,
SEGOrderDetailSectionHeadViewDelegate,
SEGOrderDetailButtonViewDelegate,
ControlTemplateViewControllerDelegate,
SEGOrderTrackCellDelegate,
SEGOrderHandleControllerDelegate
>
{
    BOOL isOpenDetail;//是否展开详情
    BOOL isOpenTrack;//是否展开轨迹
    SEGOrderHandleController *_handleVC;//工单处页面
    BOOL _isDevcieOrPatrolIsToDeal;//是否是工单处理页面接单后点击了巡更或巡检工单的直接处理
    BOOL isToDeal;//是否是直接处理
    NSString *tureOrderId;//工单id
    ControlTemplateViewController* templateVC;//生成所有控件的VC
}

@property (nonatomic, assign) __block BOOL loadDataFaild;//记录接口失败，只要失败其他接口回调也不刷新界面
@property (nonatomic, assign) __block NSInteger finishCount;//记录接口请求成功个数

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)SEGOrderDetailSectionHeadView *headerView;/**组头 */
@property(nonatomic,strong)NSMutableArray *dataArray;/**列表数据源 */
@property(nonatomic,strong)SEGOrderDetailModel *detailModel;/**详情数据模型 */
@property(nonatomic,strong)NSMutableArray *buttonDataSource;/**底部按钮需要的数据源 */
@property(nonatomic,strong)SEGOrderDetailButtonView *handleButtonView;/**底部按钮 */
@property(nonatomic,strong)NSMutableArray *orderDealDataArray;/**工单处理数据源 */
//@property (nonatomic, strong)SEGOrderSubmitManager *submitManager;/**提交管理类 */
@property (nonatomic, strong) NSMutableDictionary *foldTextDictionry; /**折叠的文字数据 */
@property (nonatomic, strong) NSMutableDictionary *cellHightDict; /** cell高度缓存 */

@end

@implementation SEGOrderDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"工单详情";
    [self showCustomNavigationBackButton];
    tureOrderId = _orderDict[@"serviceOrderId"];
    _detailModel = [[SEGOrderDetailModel alloc] init];
    [self initView];
    [self loadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleServiceListRefreshNotification:) name:NOTI_SEGORDERMYSERVICE_LIST_REFRESH object:nil];
}

- (void)handleServiceListRefreshNotification:(NSNotification *)notifi {
    self.needReloadData = YES;
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (@available(iOS 11.0, *)) {
        _tableView.estimatedRowHeight = 180;
    }
    if (self.needReloadData) {
        self.needReloadData = NO;
        [self loadData];
    }
}

/**
 初始化控件
 */
-(void)initView {
    //控件初始化
    templateVC = [[ControlTemplateViewController alloc] init];
    templateVC.fundelegate = self;
    templateVC.mastVC = self;
    templateVC.orderId = tureOrderId;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.bottom.mas_equalTo(0);
    }];
}
/**
 拉取数据 - 有网络拉取数据 没网络展示缓存
 */
-(void)loadData {
    [self loadOnLineDetailData];
}

/**
 拉取详情信息
 */
-(void)loadOnLineDetailData {
    //网络数据
    self.finishCount  = 1;//4个接口全部拉取完成才渲染界面 - 工单查询历史工单只需要3个接口 设置为1 其他入口设置为0
    self.loadDataFaild = NO;//任何一个失败停止渲染
    NSString *organId =  [SEGUtils ValueToString:_orderDict[@"organId"]];
    //动作表单信息
    //查询和历史工单进来不拉取动作表单接口
    self.finishCount  = 0;
    NSDictionary *actionParam = @{@"serviceOrderId":tureOrderId,
                                  @"organId":organId,
                                  @"custId" : [SEGUtils ValueToString:[SEGProfileManager sharedManager].profile.custId]
                                  };
    WeakSelf;
    [[SEGOrderDetailManager sharedManager] getActionListWith:actionParam finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed ) {
            if (weakSelf.loadDataFaild == NO) {
                weakSelf.detailModel.actions = [self updateOrderDetailModel_actionsWith:result];
                weakSelf.finishCount ++;
                [weakSelf loadSuccessAction];
            }
        }
        else{
            [weakSelf loadFaildActionWith:errorMessage];
        }
    }];

    //来源信息
    [SVProgressHUD show];

    NSDictionary *sourceParam = @{@"serviceOrderId":tureOrderId,
                                  @"organId":organId};
    [[SEGOrderDetailManager sharedManager] getOrderBaseInfoWith:sourceParam finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed ) {
            if (weakSelf.loadDataFaild == NO) {
                weakSelf.detailModel.baseInfos = [self updateOrderDetailModel_baseInfoWith:result];
                weakSelf.finishCount ++;
                [weakSelf loadSuccessAction];
            }
        }
        else{
            [weakSelf loadFaildActionWith:errorMessage];
        }
    }];


    //详情信息
    NSDictionary *detailParam =  @{@"serviceOrderId":tureOrderId,
                                   @"organId":organId};;
    [[SEGOrderDetailManager sharedManager] getOrderDetailWith:detailParam finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed ) {
            if (weakSelf.loadDataFaild == NO) {
                weakSelf.detailModel.detailInfos = [self updateOrderDetailModel_detailInfoWith:result];
                weakSelf.finishCount ++;
                [weakSelf loadSuccessAction];
            }
            
        }
        else{
            [weakSelf loadFaildActionWith:errorMessage];
        }
    }];

    //轨迹信息
    NSDictionary *trackParam =  @{@"serviceOrderId":tureOrderId,
                                  @"organId":organId};
    [[SEGOrderDetailManager sharedManager] getOrderTrackListWith:trackParam finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed ) {
            if (weakSelf.loadDataFaild == NO) {
                weakSelf.detailModel.trackInfos = [self updateOrderDetailModel_trackInfoWith:result];
                weakSelf.finishCount ++;
                [weakSelf loadSuccessAction];
            }
        }
        else{
            [weakSelf loadFaildActionWith:errorMessage];
        }
    }];
    
}


/**
 接口拉取失败操作
 */
-(void)loadFaildActionWith:(NSString *)message
{
    [SVProgressHUD dismiss];
    self.loadDataFaild = YES;
    if (_detailModel == nil) {
        [SEGAlertView showTmepMessageWithMessage:message];
    }
}

/**
 接口请求成功
 */
- (void)loadSuccessAction {
    if (self.finishCount == 4) {
        //拿到数据
        [SVProgressHUD dismiss];
        //配置数据
        [self configTableViewDataSourceWithDetailModel:_detailModel];
        //刷新界面
        [self refreshViews];
    }
}

/**
 更新view
 */
- (void)refreshViews {
    [self.tableView reloadData];
    BOOL isHiddenHandleView = self.buttonDataSource.count == 0;
    [self.handleButtonView removeFromSuperview]; // 置空前先从当前界面移除
    self.handleButtonView = nil; // 刷新页面的时候需要重置
    self.handleButtonView.hidden = isHiddenHandleView;
    [self.view addSubview:self.handleButtonView];

    [self.handleButtonView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(44 + LYSafeAreaBottom());
    }];
    
    if (isHiddenHandleView) {
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view);
        }];
    } else {
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-44 - LYSafeAreaBottom());
        }];
    }
}


#pragma mark - ================<UITableViewDelegate>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //详细信息使用老版本布局，多个cell复用
    NSDictionary *dict = _dataArray[section];
    NSArray *array = [dict valueForKey:@"orderDetail"];
    if (array) {
        return array.count;
    }
    
    //新版本布局 每组一个cell
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id data = _dataArray[indexPath.section];
    
    switch (indexPath.section) {
        case 0:
        {
            return [self createOrderSourceCellWithData:data];
            break;
        }
        case 1:
        {
            return [self createOrderDetailCellWithData:data indexPath:indexPath];
            break;
        }
        case 2:
        {
            return [self createOrderTrackCellWithData:data];
            break;
        }
       
    }
    return nil;
}

/**
 复用创建来源cell
 @return cell
 */
-(SEGOrderSourceCell *)createOrderSourceCellWithData:(id )data {
    SEGOrderSourceCell *sourceCell = [_tableView dequeueReusableCellWithIdentifier:kSourceCellId];
    if (sourceCell == nil) {
        sourceCell = [SEGOrderSourceCell viewFromXIB];
    }
    sourceCell.selectionStyle = UITableViewCellSelectionStyleNone;
    SEGOrderDetailModel *mod = [data valueForKey:@"orderSource"];
    [sourceCell paddingDataWithMod:mod];
    
    return sourceCell;
}

/**
 复用创建详情cell
 @return cell
 */
-(SEGOrderDetailCell *)createOrderDetailCellWithData:(id)data indexPath:(NSIndexPath *)indexPath
{
    SEGOrderDetailCell *detailCell = [_tableView dequeueReusableCellWithIdentifier:kDetailCellId ];
    if (detailCell == nil) {
        detailCell = [[SEGOrderDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDetailCellId];
    }
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[data valueForKey:@"orderDetail"]];
    detailCell.indexPath = indexPath;
    detailCell.orderId = tureOrderId;
    detailCell.controller =  self;
    
    // 获取cell的折叠选中状态
    NSString *key = [NSString stringWithFormat:@"%@",indexPath];
    // yes:展开 no：折叠
    detailCell.foldStatus = [self.foldTextDictionry[key] boolValue];
    WeakSelf;
    detailCell.foldButtonTapBlock = ^(BOOL isSelect) {
        weakSelf.foldTextDictionry[key] = @(isSelect);
        [weakSelf.tableView reloadData];
    };
    
    [detailCell paddingDataWithDataArray:array];
    return detailCell;
}

/**
 复用创建轨迹cell
 @return cell
 */
-(SEGOrderTrackCell *)createOrderTrackCellWithData:(id )data
{
    SEGOrderTrackCell *trackCell = [_tableView dequeueReusableCellWithIdentifier:kTrackCellId];

    SEGOrderDetailModel *mod = [data valueForKey:@"orderTrack"];
    trackCell.delegate = self;
    trackCell.parentVC = self;
    trackCell.detailModel = _detailModel;
    [trackCell paddingDataWithMod:mod];
    
    return trackCell;
    
}


- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dict = _dataArray[section];
    if ([[dict allKeys] containsObject:@"orderDetail"]) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 0.5)];
        headerView.backgroundColor = kColor_W;
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, LYScreenWidth() - 30, 0.5)];
        lineView.backgroundColor = kColor_L2;
        [headerView addSubview:lineView];
        return headerView;
    }
    else {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = [NSString stringWithFormat:@"%@",indexPath];
    [self.cellHightDict setObject:@(cell.frame.size.height) forKey:key];
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath {
    NSString *key = [NSString stringWithFormat:@"%@",indexPath];
    CGFloat height = [[self.cellHightDict objectForKey:key] floatValue];
    if (height == 0) height = 88.f;
    return height;
}

#pragma mark - ================<UITableViewDataSource>===============
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSDictionary *dict = _dataArray[section];
    if ([[dict allKeys] containsObject:@"orderDetail"]) {
       return 0.5;
    }
    return 0.1;
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == self.dataArray.count-1) {
        return 0.1;
    }
    if (section == 0) {
        return 0.01;
    }
   return  10;
    
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    
    return UITableViewAutomaticDimension;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 10)];
    headView.backgroundColor = kColor_bg;
    if (section==0) {
        headView.frame = CGRectMake(0, 0, LYScreenWidth(), 0);
    }else{
        headView.frame = CGRectMake(0, 0, LYScreenWidth(), 10);
    }
    return headView;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


-(void)openUserNameRefreshTableView
{
    [_tableView reloadData];
}

#pragma mark - ================<界面数据源配置>===============

/**
  基本信息和轨迹信息都使用模型操作
  详细信息兼容控件模板，需要转化为字典操作
 
 */

/**
 配置数据源
  */
-(void)configTableViewDataSourceWithDetailModel:(SEGOrderDetailModel *)mod
{
    [self.dataArray removeAllObjects];
    [self.buttonDataSource removeAllObjects];
    [self.orderDealDataArray removeAllObjects];
    
    //1.配置基本信息视图数据源
    [self configOrderSourceDataWithDetailModel:mod];
    //2.配置详情信息视图数据源
    [self configOrderDetailDataWithDetailModel:mod];
    //3.配置轨迹信息视图数据源
    [self configOrderTrackDataWithDetailModel:mod];
    //4.配置底部按钮数据源
    [self configOrderButtonDataWithModel:mod];
}

/**
 配置基本信息数据源
  */
-(void)configOrderSourceDataWithDetailModel:(SEGOrderDetailModel *)mod
{
    //第一组
    NSMutableDictionary *dict  = [[NSMutableDictionary alloc] init];
    [dict setObject:mod forKey:@"orderSource"];
    
    [self.dataArray addObject:dict];
    
}


/**
 配置详情信息数据源
  */
-(void)configOrderDetailDataWithDetailModel:(SEGOrderDetailModel *)mod
{
    
    NSArray *formlist = [[NSArray alloc] initWithArray:mod.detailInfos];
    NSMutableArray *orderDetail = [[NSMutableArray alloc] init];
    //遍历控件信息 - 组装成界面展示需要的数据
    [formlist enumerateObjectsUsingBlock:^(SEGTemplateModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSDictionary *dict = model.mDictionary;
       [orderDetail addObjectsFromArray:[self configOrderDetailReadOnlyDataSource:dict]];
        
    }];
    
    // 按照提单页面控件顺序排序
    orderDetail = [self seqTemplateDisgroupWith:orderDetail];
    
    //第三组
    NSMutableDictionary *dict  = [[NSMutableDictionary alloc] init];
    [dict setObject:orderDetail forKey:@"orderDetail"];
    [self.dataArray addObject:dict];
    
}

/**
 对控件进行分组和排序
 （排序逻辑和提单页面一致  SEGOrderInputDetailViewController --> ControlTemplateViewControler）

 @param templateArray 原始数据
 @return 排序之后的数据
 */
-(NSMutableArray *)seqTemplateDisgroupWith:(NSMutableArray *)templateArray{
    NSMutableArray *seqData = [[NSMutableArray alloc] initWithArray:templateArray];
    if (templateArray.count == 0) {
        return seqData;
    }
    //按照组冒泡排序
    for (int  i =0; i<[seqData count]-1; i++) {
        for (int j = i+1; j<[seqData count]; j++) {
            SEGTemplateModel *model_I = [SEGTemplateModel yy_modelWithDictionary:seqData[i]];
            SEGTemplateModel *model_J = [SEGTemplateModel yy_modelWithDictionary:seqData[j]];
            if ([model_I.disGroupid intValue]>[model_J.disGroupid intValue]) {
                //交换
                [seqData exchangeObjectAtIndex:j withObjectAtIndex:i];
            }
        }
    }
    
    //按照seq冒泡排序
    for (int  i =0; i<[seqData count]-1; i++) {
        
        for (int j = i+1; j<[seqData count]; j++) {
            SEGTemplateModel *model_I = [SEGTemplateModel yy_modelWithDictionary:seqData[i]];
            SEGTemplateModel *model_J = [SEGTemplateModel yy_modelWithDictionary:seqData[j]];
            if ([model_I.seq intValue]>[model_J.seq intValue] && [model_I.disGroupid intValue] == [model_J.disGroupid intValue]) {
                //交换
                [seqData exchangeObjectAtIndex:j withObjectAtIndex:i];
            }
        }
    }
    return seqData;
}

/**
 配置底部按钮数据源和处理界面数据源
  */
-(void)configOrderButtonDataWithModel:(SEGOrderDetailModel *)model
{
    NSArray *actions  = model.actions;
    [self.buttonDataSource removeAllObjects];

    // 没有动作编码 & 不可撤单
    BOOL canCancel = self.detailModel.baseInfos.canCancel.boolValue;
    if (actions.count == 0 && !canCancel) {
        return;
    }
    [actions enumerateObjectsUsingBlock:^(SEGOrderActionModel *actionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.buttonDataSource addObject:actionModel];
    }];
    
    // 添加撤单动作
    if (canCancel) {
        SEGOrderActionModel *model = [[SEGOrderActionModel alloc] init];
        model.actionName = @"撤销";
        model.isCancel = YES;
        [self.buttonDataSource addObject:model];
    }
}

/**
 处理核销控件 - 拆分为三个显示
  */
-(NSArray *)configOrderDetailReadOnlyDataSource:(NSDictionary *)dict
{
    NSMutableArray *readArray = [[NSMutableArray alloc ] init];
    if (!dict) {
        return readArray;
    }
    
    BOOL isOnlyRead = [[SEGUtils ValueToString:dict[@"readable"]] isEqualToString:@"1"] && [[SEGUtils ValueToString:dict[@"writable"]] isEqualToString:@"0"] ;
    //控件是否有输入
    BOOL isHaveValue = [NSString stringWithFormat:@"%@",dict[@"attrValue"]].length;
    if (isOnlyRead && isHaveValue) {//只读,并且有值
        //核销需要特殊处理
        if ([dict[@"widgetType"] isEqualToString:@"homeservices"]){//到家服务控件，要拆分为3个控件，有偿服务费，核销控件，总价控件
            [self configHomeservicesDataArrayWith:readArray data:dict];
        }
        //差评原因控件拆分成两个label控件
        else if ([dict[@"widgetType"] isEqualToString:@"evaluate_reply"]){
            id attrValue = dict[@"attrValue"];
            NSDictionary *attrDict = [attrValue yy_modelToJSONObject];
            NSString *levelStr = attrDict[@"evaluate"];
            levelStr = [NSString stringWithFormat:@"%ld星",(long)[levelStr integerValue]];
            NSDictionary *evalueLevel = @{@"title":@"评价",@"attrValue":levelStr,@"widgetType":@"evaluate_reply"};
            NSDictionary *evalueReason = @{@"title":dict[@"title"],@"attrValue":attrDict[@"message"],@"widgetType":@"evaluate_reply"};
            [readArray addObject:evalueLevel];
            [readArray addObject:evalueReason];
        }
        else{
            //拿到只读控件模板信息
            [readArray addObject:dict];
        }
    }
    return readArray;
}


/**
 拆分到家服务费控件
 */
-(void)configHomeservicesDataArrayWith:(NSMutableArray *)readArray data:(NSDictionary *)data
{
    NSDictionary *dict = data;
    __block CGFloat serPrice = 0;
    id attrValue = dict[@"attrValue"];
    NSDictionary *attrDict = [attrValue yy_modelToJSONObject];
    //1.先取服务清单
    NSMutableArray *valueArr1 = [[NSMutableArray alloc] init];
    NSArray *serviceArray = attrDict[@"serviceItem"];
    [serviceArray enumerateObjectsUsingBlock:^(NSDictionary *serviceItem, NSUInteger idx, BOOL * _Nonnull stop) {
        [valueArr1 addObject:serviceItem[@"serviceName"]];
        serPrice += [serviceItem[@"price"] floatValue];
    }];
    NSString *servcieStr = [valueArr1 componentsJoinedByString:@"，"];
    NSString *serPriceStr = [NSString stringWithFormat:@"%.2f元",serPrice/100];
    servcieStr = [NSString stringWithFormat:@"%@\n共计：%@",servcieStr,serPriceStr];
    //拼接成label控件
    NSDictionary *serDict = @{@"title":dict[@"title"],
                              @"attrValue":servcieStr,
                              @"widgetType":@"label"
                              };
    [readArray addObject:serDict];
    
    //2.拿核销控件
    NSMutableArray *valueArr2 = [[NSMutableArray alloc] init];
    __block CGFloat materPrice = 0;
    NSArray *materelsArray = attrDict[@"partsItem"];
    [materelsArray enumerateObjectsUsingBlock:^(NSDictionary *materelItem, NSUInteger idx, BOOL * _Nonnull stop) {
        [valueArr2 addObject:[NSString stringWithFormat:@"%@×%@",materelItem[@"goodsName"],materelItem[@"useCount"]]];
        if ([materelItem[@"verificationType"] isEqualToString:@"2"]) {
            materPrice += [materelItem[@"price"] floatValue] * [materelItem[@"useCount"] integerValue] ;
        }
    }];
    NSString *materelStr = [valueArr2 componentsJoinedByString:@"，"];
    NSString *materPriceStr = [NSString stringWithFormat:@"%.2f元",materPrice/100];
    materelStr = [NSString stringWithFormat:@"%@\n共计：%@",materelStr,materPriceStr];
    //拼接成label控件
    NSDictionary *materDict = @{@"title":@"物料领用",
                              @"attrValue":materelStr,
                              @"widgetType":@"label"
                              };
    [readArray addObject:materDict];
    
    //3.总价显示
    NSString *totalFeeStr = attrDict[@"totalFee"];
    NSString *totalStr = [NSString stringWithFormat:@"%.2f元",[totalFeeStr floatValue]/100];
    //拼接成label控件
    NSDictionary *priceDict = @{@"title":@"总价",
                                @"attrValue":totalStr,
                                @"widgetType":@"label"
                                };
    [readArray addObject:priceDict];
}

/**
 配置工单轨迹数据源
  */
-(void)configOrderTrackDataWithDetailModel:(SEGOrderDetailModel *)mod
{
    
    NSMutableDictionary *orderTrack = [[NSMutableDictionary alloc] init];
    [orderTrack setObject:_detailModel forKey:@"orderTrack"];
    
    if (self.dataArray.count > 0) {
        [self.dataArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[dict allKeys] containsObject:@"orderTrack"]) {//有就更新，没有就添加
                [_dataArray removeObject:dict];
                *stop = YES;
            }
            
        }];
    };
    
    [_dataArray addObject:orderTrack];
    
}

#pragma mark - ================<底部按钮代理回调>===============
/**
 选择了某种处理方式回调
 */
-(void)clickBottomButtonAction:(SEGOrderActionModel *)actionModel
{
    // 4.9.10 新增撤单功能
    if (actionModel.isCancel) {
        SEGOrderCancelViewController *cancelVC = [[SEGOrderCancelViewController alloc] init];
        cancelVC.organID = self.detailModel.baseInfos.organId;
        cancelVC.serviceOrderID = self.detailModel.baseInfos.serviceOrderId;
        [self.navigationController pushViewController:cancelVC animated:YES];
        return;
    }
    /*
     4.8.0 修改跳转支付逻辑
     old：判断actionModel.actionCode == @"REF_USER_PAY"
     new：判断 queryOrderBaseInfo.json 接口返回的基本信息的resultCode字段 == @"NODE_DS_PAID_NEW"
     */
    if ([self.detailModel.baseInfos.resultCode isEqualToString:@"NODE_DS_PAID_NEW"]) {
        // 支付环节
        SEGOrderPayViewController *orderPayVC = [[SEGOrderPayViewController alloc] init];
        orderPayVC.serviceOrderId = tureOrderId;
        orderPayVC.organId = _detailModel.baseInfos.organId;
        orderPayVC.trackId = _detailModel.baseInfos.trackId;
        [self.navigationController pushViewController:orderPayVC animated:YES];
    } else {//提交表单数据
        //1.有处理表单，直接跳转到处理界面
        if (actionModel.formList.count > 0) {
            _handleVC = [[SEGOrderHandleController alloc] init];
            _handleVC.title = actionModel.actionName;
            _handleVC.detailModel = _detailModel;
            _handleVC.actionModel = actionModel;
            _handleVC.delegate = self;
            [self.navigationController pushViewController:_handleVC animated:YES];
        }
    }
}

/**
 返回上级界面
 */
-(void)popToRootViewContorller:(id)result
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}


#pragma mark - ================<工单处理页面回调>===============
/**
 工单处理页回调刷新待办
 */
-(void)orderHandleSumbitOrderDetailFormDataSucessRefreshPendingList:(NSString *)orderId
{
    [self callPendingListRefreshUI];
}

/**
 刷新详情页回调
 */
-(void)refreshDetailViewControllerWithIsDevcieOrPatrolIsToDeal:(BOOL)isDevcieOrPatrolIsToDeal
{
    _isDevcieOrPatrolIsToDeal = isDevcieOrPatrolIsToDeal;
    [self.dataArray removeAllObjects];
    [self.buttonDataSource removeAllObjects];
    [self.orderDealDataArray removeAllObjects];
    [self loadData];
}
/**
 刷新待办列表
 */
-(void)callPendingListRefreshUI
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(orderDetailSumbitOrderDetailFormDataSucessRefreshPendingList:)]) {
        [self.delegate orderDetailSumbitOrderDetailFormDataSucessRefreshPendingList:tureOrderId];
    }
}


/**
 更新详情模型里面的工单基本信息数据
 */
-(SEGOrderBaseInfoModel *)updateOrderDetailModel_baseInfoWith:(NSDictionary *)dict
{
    NSDictionary *data = dict[@"data"];
    if (![data isKindOfClass:[NSDictionary class]]) {
        return [[SEGOrderBaseInfoModel alloc] init];
    }
    SEGOrderBaseInfoModel *baseModel = [SEGOrderBaseInfoModel initWithDictionary:data];
    baseModel = [SEGOrderBaseInfoModel yy_modelWithDictionary:data];
    return baseModel;
}

/**
 更新详情模型里面的工单详情信息
 */
-(NSArray *)updateOrderDetailModel_detailInfoWith:(NSDictionary *)dict{
    NSArray *formData = dict[@"data"];
    NSMutableArray *formList = [[NSMutableArray alloc] init];
    if (![formData isKindOfClass:[NSArray class]] || formData == nil || formData.count == 0) {
        return formList;
    }
    [formData enumerateObjectsUsingBlock:^(NSDictionary *templateDict, NSUInteger idx, BOOL * _Nonnull stop) {
        
        SEGTemplateModel *model = [SEGTemplateModel initWithDictionary:templateDict];
        [formList addObject:model];
    }];
    return formList;
}

/**
 更新工单详情里面的工单轨迹模型
 */
-(NSArray *)updateOrderDetailModel_trackInfoWith:(NSDictionary *)dict{
    
    NSArray *trackInfo = dict[@"data"];
    NSMutableArray *trackInfoArray = [[NSMutableArray alloc] init];
    if (trackInfo == nil || ![trackInfo isKindOfClass:[NSArray class]]) {
        return trackInfoArray;
    }
    
    [trackInfo enumerateObjectsUsingBlock:^(NSDictionary *track, NSUInteger idx, BOOL * _Nonnull stop) {
        
        SEGOrderTrackInfoModel *model= [SEGOrderTrackInfoModel initWithDictionary:track];
        [trackInfoArray addObject:model];
        
    }];
    return trackInfoArray;
}

/**
 更新工单详情里面的动作表单数据
 */
-(NSArray *)updateOrderDetailModel_actionsWith:(NSDictionary *)dict{
    
    NSDictionary *data =  dict[@"data"];
    if (![data isKindOfClass:[NSDictionary class]]) {
        return @[];
    }
    
    NSArray *actions = data[@"actionList"];
    NSMutableArray *actionsArray = [[NSMutableArray alloc] init];
    if (actions == nil || ![actions isKindOfClass:[NSArray class]]) {
        return actionsArray;
    }
    
    [actions enumerateObjectsUsingBlock:^(NSDictionary *action, NSUInteger idx, BOOL * _Nonnull stop) {
        
        SEGOrderActionModel *model= [SEGOrderActionModel initWithDictionary:action];
        [actionsArray addObject:model];
        
    }];
    return actionsArray;
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight()-kNavigationBarAndStatusBarHeight-44) style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 200;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kColor_bg;
        [_tableView registerNib:[UINib nibWithNibName:kTrackCellId bundle:nil] forCellReuseIdentifier:kTrackCellId];
        _tableView.height = LYScreenHeight()-kNavigationBarAndStatusBarHeight;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

-(NSMutableArray *)orderDealDataArray{
    if (!_orderDealDataArray) {
        _orderDealDataArray = [[NSMutableArray alloc] init];
    }
    return _orderDealDataArray;
}
-(NSMutableArray *)buttonDataSource{
    if (!_buttonDataSource) {
        _buttonDataSource = [[NSMutableArray alloc] init];
    }
    return _buttonDataSource;
}

- (SEGOrderDetailSectionHeadView *)headerView
{
    _headerView = [[SEGOrderDetailSectionHeadView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 44)];
    _headerView.backgroundColor = kColor_W;
    _headerView.delegate = self;
    return _headerView;
}

- (SEGOrderDetailButtonView *)handleButtonView
{
    if (_handleButtonView == nil) {
        _handleButtonView = [[SEGOrderDetailButtonView alloc] initWithFrame:CGRectMake(0, LYScreenHeight() - kNavigationBarAndStatusBarHeight - 44 - LYSafeAreaBottom(), LYScreenWidth(), 44 + LYSafeAreaBottom()) Arr:_buttonDataSource];
        _handleButtonView.backgroundColor = kColor_T;
        _handleButtonView.hidden = NO;
        _tableView.height = LYScreenHeight()-kNavigationBarAndStatusBarHeight-44-LYSafeAreaBottom();
        _handleButtonView.delegate = self;
    }
    return _handleButtonView;
}

- (NSMutableDictionary *)foldTextDictionry {
    if (!_foldTextDictionry) {
        _foldTextDictionry = [NSMutableDictionary dictionary];
    }
    return _foldTextDictionry;
}

- (NSMutableDictionary *)cellHightDict {
    if (!_cellHightDict) {
        _cellHightDict = [NSMutableDictionary new];
    }
    return _cellHightDict;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
   
}

@end
